package com.s63.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.s63.entity.User;
import com.s63.mapper.UserMapper;
import com.s63.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import static com.s63.modules.rabbit.RabbitConfig.NAME_EXCHANGE_DIRECT;
import static com.s63.modules.rabbit.RabbitConfig.NAME_ROUTING_KEY_USER_ADD;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author baomidou
 * @since 2023-11-06
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public void asyncSave(User user) {
        if (StringUtils.isEmpty(user.getPassword())) throw new RuntimeException("密码不能为空");
        User findUser = getOne(Wrappers.lambdaQuery(User.class).eq(User::getUserName, user.getUserName()));
        if (findUser != null) throw new RuntimeException("用户已经存在");
        rabbitTemplate.convertAndSend(NAME_EXCHANGE_DIRECT, NAME_ROUTING_KEY_USER_ADD, user);
        log.info("发送用户创建消息成功");
    }

    @Override
    public boolean save(User entity) {
        entity.setPassword(passwordEncoder.encode(entity.getPassword()));
        return super.save(entity);
    }

    @Override
    public boolean updateById(User entity) {
        if (StringUtils.hasText(entity.getPassword())) {
            entity.setPassword(passwordEncoder.encode(entity.getPassword()));
        }
        return super.updateById(entity);
    }
}
